package xyz.haijin.shiro.service.impl;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.haijin.shiro.dao.UserDAO;
import xyz.haijin.shiro.entity.User;
import xyz.haijin.shiro.service.UserService;
import xyz.haijin.shiro.util.Constants;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDAO userDAO;

    @Override
    public User doLogin(String email, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(email, password);
        try {
            token.setRememberMe(true);
            subject.login(token);
            Session session = subject.getSession();
            User user = getUserByEmail(email);
            session.setAttribute(Constants.SESSION_USER, user);
            return user;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public User getUserByEmail(String email) {
        return userDAO.getUserByEmail(email);
    }

    @Override
    public List<User> getUserList() {
        return userDAO.getUserList();
    }

    @Override
    public List<Integer> getUserRoleIds(Integer userId) {
        return userDAO.getUserRoleIds(userId);
    }

    @Override
    public void addUserRole(Integer userId, Integer[] roleIds) {
        userDAO.deleteUserRole(userId);
        Map<String, Integer> param = new HashMap<>();
        param.put("userId", userId);
        for (Integer roleId : roleIds) {
            param.put("roleId", roleId);
            userDAO.addUserRole(param);
        }
    }
}
